<?php
/**
 * Created by PhpStorm.
 * User: castle
 * Date: 15-3-27
 * Time: 下午7:52
 */
class TsySession implements \SessionHandlerInterface{
	private $handler;
	private $get_result;
	private $host = '127.0.0.1';
	private $port = 6379;
	private $auth = 'agejifopjafjafjiofj3342jdaopwifje';
	private $expire = 1200;
	private $prefix ='S_';
	private $connect = false;
	public function __construct(){
		if(defined('APPID')){
			$this->prefix = APPID;
		}
		if ( !class_exists('Redis') ) {
			E(L('_NOT_SUPPERT_').':redis');
			return false;
		}
		$this->handler = new \Redis();
	}
	function read($session_id){
		if($this->connect === false && $this->connection() === false){
			E('Can`t Connect To Redis Server');
			return false;
		}
		$this->get_result = $this->handler->get($this->getSessionID($session_id));
		return $this->get_result;
	}
	function destroy($session_id){
		if($this->connect === false && $this->connection() === false){
			E('Can`t Connect To Redis Server');
			return false;
		}
		return $this->handler->delete($this->getSessionID($session_id));
	}
	function gc($maxlifetime){
		return true;
	}
	function write($session_id,$session_data){
		if($this->connect === false && $this->connection() === false){
			E('Can`t Connect To Redis Server');
			return false;
		}
		GLog('RedisSet:'.$this->handler->get($this->getSessionID($session_id)));
		return $this->handler->setex($this->getSessionID($session_id),$this->expire,$session_data);
	}
	function open($save_path,$session_id){
		return $this->connection();
	}
	function close(){
		$this->handler->close();
		return true;
	}
	function connection (){
		if($this->handler->pconnect($this->host,$this->port) === false){
			E('Can`t Connect To Redis');
			return false;
		}
		if($this->handler->auth($this->auth) === false){
			E('Can`t Auth To Redis');
			return false;
		}
//		Log::record('Redis Server Connect Success');
		$this->connect = true;
		return true;
	}
	function getSessionID($session_id){
		return md5($this->prefix.$session_id);
	}
}
$handler = new TsySession();
session_set_save_handler($handler,true);